package com.xyzwps.server.paimon.graphql.scalar

import com.xyzwps.server.paimon.value.Phone
import graphql.GraphQLContext
import graphql.execution.CoercedVariables
import graphql.language.NullValue
import graphql.language.StringValue
import graphql.language.Value
import graphql.schema.Coercing
import graphql.schema.GraphQLScalarType
import java.util.Locale


internal object PhoneCoercing : Coercing<Phone, String> {
    override fun serialize(dataFetcherResult: Any, ctx: GraphQLContext, locale: Locale): String =
        when (dataFetcherResult) {
            is Phone -> dataFetcherResult.value
            else -> throw IllegalArgumentException("Invalid phone number")
        }

    override fun parseValue(input: Any, ctx: GraphQLContext, locale: Locale): Phone =
        when (input) {
            is Phone -> input
            is String -> Phone(input)
            else -> throw IllegalArgumentException("Invalid phone number")
        }

    override fun parseLiteral(input: Value<*>, vars: CoercedVariables, ctx: GraphQLContext, locale: Locale): Phone? =
        when (input) {
            is StringValue -> Phone(input.value)
            is NullValue -> null
            else -> throw IllegalArgumentException("Invalid phone number")
        }
}


val PHONE_SCALAR: GraphQLScalarType = GraphQLScalarType.newScalar()
    .name("Phone")
    .description("Phone number")
    .coercing(PhoneCoercing)
    .build()
